﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MSBTC.Model;

namespace MSBTC.WinForms
{
    public partial class TransferEquipForm : Form
    {
        PMSContext dbcontext = new PMSContext();
        private int[] numitemselcted = new int[1000];
        private string[] itemselected = new string[1000];
        Equipment dbeqp = new Equipment();
        ProjEquip dbpjeq = new ProjEquip();

        public TransferEquipForm()
        {
            InitializeComponent();
        }

        private void TransferEquipForm_Load(object sender, EventArgs e)
        {
            cmbProjT.SelectedIndex = 0;
            cmbProjF.SelectedIndex = 0;

            var pname = (from p in dbcontext.Projects
                         select p).ToList();
            if (pname != null)
            {
                foreach (var pn in pname)
                {
                    cmbProjF.Items.Add(pn.Project_Name);
                    cmbProjT.Items.Add(pn.Project_Name);
                }
            }
            else
            {
                MessageBox.Show("There are records in project, please add new Project in main menu", "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Hide();
            }

        }

        private void cmbProjF_SelectedIndexChanged(object sender, EventArgs e)
        {
            lbEquip.Items.Clear();
            if (cmbProjT.SelectedIndex == 0 && cmbProjF.SelectedIndex == 0 || cmbProjF.SelectedIndex == 0 || cmbProjF.SelectedIndex != 0 && cmbProjT.SelectedIndex == 0)
            {
                btnSave.Enabled = false;
                btnfront.Enabled = false;
            }
            else
            {
                btnSave.Enabled = true;
                btnfront.Enabled = true;
            }

            if (cmbProjF.SelectedItem != cmbProjT.SelectedItem)
            {
                if (cmbProjF.SelectedIndex != 0)
                {
                    var pid = (from id in dbcontext.Projects
                               where id.Project_Name == cmbProjF.SelectedItem
                               select id).SingleOrDefault();
                    if (pid != null)
                    {
                        var prjeqp = (from pe in dbcontext.PrjEqs
                                      where pe.Projectid_FK == pid.Projectid_PK
                                      select pe).ToList();
                        if (prjeqp != null)
                        {
                            foreach (var prj in prjeqp)
                            {
                                var eq = dbcontext.Equipments.Find(prj.Equipid_FK);
                                if (eq != null)
                                {
                                    lbEquip.Items.Add(eq.Equip_Name);
                                }
                                else
                                {
                                    MessageBox.Show("There are no Equipments assigned to this current project, Please assign Equipment to this Project", "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    cmbProjF.SelectedIndex = 0;
                                    return;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Selected Project name was conflict with other Project name, Please select different Project name", "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbProjF.SelectedIndex = 0;
                return;
            }
        }

        private void cmbProjT_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblsct.Items.Clear();
            if (cmbProjT.SelectedIndex == 0 && cmbProjF.SelectedIndex == 0 || cmbProjF.SelectedIndex == 0 || cmbProjT.SelectedIndex == 0 && cmbProjF.SelectedIndex != 0)
            {
                btnSave.Enabled = false;
                btnfront.Enabled = false;
                txtqty.Enabled = false;
            }
            else
            {
                btnSave.Enabled = true;
                btnfront.Enabled = true;
                txtqty.Enabled = true;
            }

            if (cmbProjT.SelectedItem != cmbProjF.SelectedItem)
            {
                if (cmbProjT.SelectedIndex != 0)
                {
                    var pid = (from id in dbcontext.Projects
                               where id.Project_Name == cmbProjT.SelectedItem
                               select id).SingleOrDefault();
                    if (pid != null)
                    {
                        var prjeqp = (from pe in dbcontext.PrjEqs
                                      where pe.Projectid_FK == pid.Projectid_PK
                                      select pe).ToList();
                        if (prjeqp != null)
                        {
                            foreach (var prj in prjeqp)
                            {
                                var eq = dbcontext.Equipments.Find(prj.Equipid_FK);
                                lblsct.Items.Add(eq.Equip_Name);
                            }
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Selected Project name was conflict with other Project name, Please select different Project name", "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbProjT.SelectedIndex = 0;
                return;
            }
        }

        private void txtqty_TextChanged(object sender, EventArgs e)
        {
            FormHelpers help = new FormHelpers();
            //check every letters
            if (txtqty.Text != "")
            {
                if (help.SpecChar(txtqty.Text, txtqty) == false || (System.Text.RegularExpressions.Regex.IsMatch(txtqty.Text, "[^0-9]") == true))
                {
                    MessageBox.Show("Only Numeric values are allowed", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtqty.Clear();
                    return;
                }
            }
        }

        private void btnfront_Click(object sender, EventArgs e)
        {
            if (txtqty.Text != "")
            {
                if (Convert.ToInt32(txtqty.Text) <= Convert.ToInt32(lblused.Text) || Convert.ToInt32(txtqty.Text) > 0)
                {
                    if (lbEquip.SelectedIndex != -1)
                    {
                        string slctd = lbEquip.SelectedItem.ToString();
                        int qty = Convert.ToInt32(txtqty.Text);
                        int cnt = 0;
                        foreach (var item in lblsct.Items)
                        {
                            if (slctd == item)//if the selected item and item in lblsct is the same
                            {
                                //retrieve equipment to be removed in lbequip
                                var eqp = (from eq in dbcontext.Equipments
                                           where eq.Equip_Name == slctd
                                           select eq).SingleOrDefault();
                                if (eqp != null)
                                {
                                    var proj = (from p in dbcontext.Projects
                                                where p.Project_Name == cmbProjF.SelectedItem
                                                select p).SingleOrDefault();

                                    //retrieve qty with the same name in project-equipment
                                    var pjeq = (from pj in dbcontext.PrjEqs
                                                where pj.Equipid_FK == eqp.Equipmentid_PK && pj.Projectid_FK == proj.Projectid_PK
                                                select pj).SingleOrDefault();

                                    if (qty == pjeq.QuantityUsed)
                                    { //remove the item
                                        lbEquip.Items.Remove(slctd);
                                        break;
                                    }
                                   
                                }
                            }//else check if not equal to selected equipname and does not contains with the same equipname
                            else if (slctd != item && lblsct.Items.Contains(slctd) == false)
                            {
                                var eqp = (from eq in dbcontext.Equipments
                                           where eq.Equip_Name == slctd //&& qty <= eq.Quantity - eq.QtyUsed
                                           select eq).SingleOrDefault();
                                if (eqp != null)
                                {
                                    var proj = (from p in dbcontext.Projects
                                                where p.Project_Name == slctd
                                                select p).SingleOrDefault();

                                    var pjeq = (from pj in dbcontext.PrjEqs
                                                where pj.Equipid_FK == eqp.Equipmentid_PK && pj.Projectid_FK == proj.Projectid_PK
                                                select pj).SingleOrDefault();

                                    if (qty == pjeq.QuantityUsed)
                                    { //remove the item
                                        lbEquip.Items.Remove(slctd);
                                        break;
                                    }
                                    lblsct.Items.Add(slctd);
                                    break;
                                }
                            }
                        }
                        //store to an array for saving
                        List<string> itmlst = new List<string>(itemselected);
                        foreach (var arrlst in itmlst)
                        {//get all values stored in the itemselected
                            if (arrlst != null)
                            {
                                cnt += 1;
                            }
                            else
                            {
                                if (cnt > 0)
                                {
                                    break;
                                }
                                else
                                {
                                    cnt -= 1;
                                    break;
                                }

                            }
                        }
                        //set the array value where to store
                        itemselected[cnt + 1] = slctd;
                        numitemselcted[cnt + 1] = qty;
                        lblqty.Text = qty.ToString();
                        txtqty.Clear();
                    }
                }
                else
                {
                    MessageBox.Show("Please check the Quantity if not less than 0 or greater than the remaining quantity", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            else
            {
                MessageBox.Show("Please enter quantity to be transfer", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        private void lbEquip_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblused.Text = "";
            btnfront.Enabled = true;

            if (lblsct.SelectedIndex != -1)
            {
                lblsct.ClearSelected();
                //lblsct.SelectedIndex = 0;

            }
            if (lbEquip.SelectedItems.Count != 0)
            {
                txtqty.Enabled = true;
                string itmslt = lbEquip.SelectedItem.ToString();

                var proj = (from p in dbcontext.Projects
                            where p.Project_Name == cmbProjF.SelectedItem
                            select p).SingleOrDefault();
                if (proj != null)
                {
                    var eq = (from eqp in dbcontext.Equipments
                              where eqp.Equip_Name == itmslt
                              select eqp).SingleOrDefault();
                    if (eq != null)
                    {
                        var pjeq = (from pe in dbcontext.PrjEqs
                                    where pe.Equipid_FK == eq.Equipmentid_PK && pe.Projectid_FK == proj.Projectid_PK
                                    select pe).SingleOrDefault();
                        if (pjeq != null)
                        {
                            lblused.Text = pjeq.QuantityUsed.ToString();
                        }
                    }
                }

                 int indx = Array.IndexOf(itemselected, itmslt);
                 if (indx != -1)
                 {
                     int qtyindx = numitemselcted[indx];
                     lblqty.Text = qtyindx.ToString();
                 }
                 else
                 {
                     lblqty.Text = "0";
                 }
            }
            else
            {
                lblsct.SelectedItem = -1;
                txtqty.Enabled = false;
            }         
        }

        private void btnSave_Click(object sender, EventArgs e)
        {//NEEED SOME MODIFICATIONS "STUDY ALL!"
            int ctr = 0;
            try
            {
                List<string> itmlst = new List<string>(itemselected);
                foreach (var lstitm in itmlst)
                {
                    if (lstitm != null)
                    {
                        ctr += 1;
                        int eqindx = Array.IndexOf(itemselected, lstitm);
                        int qtyadd = numitemselcted[eqindx];

                        //check for existing equipment for data gathering
                        var eqp = (from eq in dbcontext.Equipments
                                   where eq.Equip_Name == lstitm
                                   select eq).SingleOrDefault();
                        if (eqp != null)
                        {//check for existing project name for data
                            var pj = (from p in dbcontext.Projects
                                      where p.Project_Name == cmbProjT.SelectedItem
                                      select p).SingleOrDefault();
                            if (pj != null)
                            {
                                //check for existing equipment in project-equipment
                                var pjeq = (from peq in dbcontext.PrjEqs
                                            where peq.Equipid_FK == eqp.Equipmentid_PK && peq.Projectid_FK == pj.Projectid_PK
                                            select peq).SingleOrDefault();
                                if (pjeq == null)
                                {
                                    //save new record in project-equipment table
                                    dbpjeq.Projectid_FK = pj.Projectid_PK;
                                    dbpjeq.Equipid_FK = eqp.Equipmentid_PK;
                                    dbpjeq.QuantityUsed = qtyadd;
                                    dbcontext.Entry(dbpjeq).State = EntityState.Added;

                                    eqp.QtyUsed += qtyadd;
                                    dbcontext.Entry(eqp).State = EntityState.Modified;

                                    dbcontext.SaveChanges();
                                }
                                else
                                {
                                    //save the modified quantity used in the a particular project                                  
                                    //eqp.QtyUsed += qtyadd;
                                    //dbcontext.Entry(eqp).State = EntityState.Modified;
                                    var prj = (from pe in dbcontext.Projects
                                               where pe.Project_Name == cmbProjF.SelectedItem
                                               select pe).SingleOrDefault();

                                    var prjeq = (from pje in dbcontext.PrjEqs
                                                 where pje.Projectid_FK == prj.Projectid_PK && pje.Equipid_FK == eqp.Equipmentid_PK
                                                 select pje).SingleOrDefault();

                                    prjeq.QuantityUsed -= qtyadd;
                                    dbcontext.Entry(prjeq).State = EntityState.Modified;

                                    pjeq.QuantityUsed += qtyadd;
                                    dbcontext.Entry(pjeq).State = EntityState.Modified;

                                    dbcontext.SaveChanges();   
                                }
                            }
                        } 
                    }
                    else if (lstitm == null && ctr == 0)
                    {
                        //create code for back button to save data... RUSH!!!!
                        MessageBox.Show("There's no record to save", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    else
                    {
                        break;
                    }
                }
                MessageBox.Show("Successfully saved", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Array.Clear(numitemselcted, 0, numitemselcted.Length);
                Array.Clear(itemselected, 0, itemselected.Length);
                lblqty.Text = "";
                Refresh();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }   
        
    }
}
